const express = require('express')
const router = express.Router()
const pool = require('../utils/pool')
const jwt = require('jsonwebtoken')
const secretKey = require('../utils/secrekey')

router.post('/login', (req, res, next) => {
  const aname = req.body.aname
  const apwd = req.body.apwd
  pool.query('select * from zh_admin where aname = ? && apwd = PASSWORD(?)', [aname, apwd], (err, result) => {
    if (err) {
      return next(err)
    }
    if (result.length === 0) {
      return res.send({
        code: 4003,
        msg: '账号或密码错误'
      })
    }

    // 生成JWT token
    const token = jwt.sign({ aname: result[0].aname }, secretKey, { expiresIn: '1 day' });
    res.send({
      code: 2000,
      msg: 'login success',
      token
    })
  })
})

module.exports = router